﻿using JYB.SummitExam.IDAL;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using JYB.SummitExam.Model;

using System.Data;
using System.Data.SqlClient;


namespace JYB.SummitExam.DAL {
	public class StudentsDAL : IUserDAL {
		//链接数据库的字符串
		public static string sqlstr = "Data Source=.;Initial Catalog=SummitExam;Integrated Security=True";
		public T Login<T>(string name, string pwd) {
			Type type = typeof(T);
			var SelectField = string.Join(",", type.GetProperties().Select(p => string.Format("[{0}]", p.Name)));
			string SqlText = "select " + SelectField + " from [" + type.Name + "] where Student_Name=@Name and Student_Pwd= @Pwd ";
			var oObject = (T)Activator.CreateInstance(type);
			using (SqlConnection con = new SqlConnection(sqlstr)) {
				con.Open();
				SqlCommand com = new SqlCommand(SqlText, con);
				com.Parameters.Add(new SqlParameter("@Name", name));
				com.Parameters.Add(new SqlParameter("@Pwd", pwd));
				SqlDataReader reader = com.ExecuteReader();
				while (reader.Read()) {
					foreach (var pop in type.GetProperties()) {
						object oValue = reader[pop.Name];
						if (oValue is DBNull) {
							pop.SetValue(oObject, null);
						}
						else {
							pop.SetValue(oObject, oValue);
						}
					}
				}
				return oObject;
			}
		}
	}
}
